/**
 * 点赞API库
 * @author HalRui
 * @version 1.0.0
 * @description 提供点赞相关的业务逻辑处理
 * @date 2025年9月27日
 */

const Likes = require('../models/likes-model');
const UserInfos = require('../models/userinfos-model');
const Videos = require('../models/videos-model');
const Comments = require('../models/comments-model');

/**
 * 点赞或取消点赞
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型（video/comment）
 * @param {number} targetId - 目标ID
 * @param {number} likeStatus - 点赞状态（1: 点赞, -1: 点踩）
 * @param {string} ip - IP地址
 * @returns {Object} 操作结果
 */
async function toggleLike(userId, targetType, targetId, likeStatus = 1, ip = '') {
    try {
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return { success: false, message: '用户不存在' };
        }

        // 验证目标是否存在
        let target;
        if (targetType === 'video') {
            target = await Videos.findOne({ videoID: targetId });
            if (!target) {
                return { success: false, message: '视频不存在' };
            }
        } else if (targetType === 'comment') {
            target = await Comments.findOne({ commentId: targetId, isDeleted: false });
            if (!target) {
                return { success: false, message: '评论不存在' };
            }
        } else {
            return { success: false, message: '无效的目标类型' };
        }

        // 执行点赞操作
        const result = await Likes.toggleLike(userId, targetType, targetId, likeStatus, ip);
        
        if (!result.success) {
            return result;
        }

        // 更新目标的点赞数
        await updateTargetLikeCount(targetType, targetId);

        return {
            success: true,
            action: result.action,
            message: getActionMessage(result.action, likeStatus),
            data: result.like.getSafeJSON()
        };
    } catch (error) {
        return { success: false, message: '点赞操作失败：' + error.message };
    }
}

/**
 * 获取点赞状态
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 * @returns {Object} 点赞状态
 */
async function getLikeStatus(userId, targetType, targetId) {
    try {
        const result = await Likes.getLikeStatus(userId, targetType, targetId);
        
        if (!result.success) {
            return result;
        }

        return {
            success: true,
            status: result.status,
            isLiked: result.status === 1,
            isDisliked: result.status === -1,
            data: result.like ? result.like.getSafeJSON() : null
        };
    } catch (error) {
        return { success: false, message: '获取点赞状态失败：' + error.message };
    }
}

/**
 * 批量获取点赞状态
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型
 * @param {Array} targetIds - 目标ID数组
 * @returns {Object} 批量点赞状态
 */
async function batchGetLikeStatus(userId, targetType, targetIds) {
    try {
        if (!Array.isArray(targetIds) || targetIds.length === 0) {
            return { success: false, message: '目标ID列表不能为空' };
        }

        const result = await Likes.batchGetLikeStatus(userId, targetType, targetIds);
        
        if (!result.success) {
            return result;
        }

        // 转换为更友好的格式
        const statusList = targetIds.map(id => ({
            targetId: id,
            status: result.statusMap[id],
            isLiked: result.statusMap[id] === 1,
            isDisliked: result.statusMap[id] === -1
        }));

        return {
            success: true,
            statusMap: result.statusMap,
            statusList
        };
    } catch (error) {
        return { success: false, message: '批量获取点赞状态失败：' + error.message };
    }
}

/**
 * 获取目标的点赞统计
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 * @returns {Object} 点赞统计
 */
async function getLikeStats(targetType, targetId) {
    try {
        const result = await Likes.getLikeStats(targetType, targetId);
        
        if (!result.success) {
            return result;
        }

        return {
            success: true,
            stats: result.stats
        };
    } catch (error) {
        return { success: false, message: '获取点赞统计失败：' + error.message };
    }
}

/**
 * 获取用户的点赞历史
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型（可选）
 * @param {number} page - 页码
 * @param {number} limit - 每页数量
 * @returns {Object} 点赞历史
 */
async function getUserLikeHistory(userId, targetType = null, page = 1, limit = 20) {
    try {
        // 验证用户是否存在
        const user = await UserInfos.findOne({ userId, isDeleted: false });
        if (!user) {
            return { success: false, message: '用户不存在' };
        }

        const result = await Likes.getUserLikeHistory(userId, targetType, page, limit);
        
        if (!result.success) {
            return result;
        }

        // 获取详细信息
        const likesWithDetails = await Promise.all(
            result.likes.map(async (like) => {
                const likeData = like.getSafeJSON();
                
                // 获取目标详细信息
                if (like.targetType === 'video') {
                    const video = await Videos.findOne({ videoID: like.targetId });
                    if (video) {
                        likeData.targetInfo = {
                            title: video.title,
                            content: video.content,
                            path: video.path,
                            viewCount: video.viewCount,
                            likeCount: video.likeCount
                        };
                    }
                } else if (like.targetType === 'comment') {
                    const comment = await Comments.findOne({ commentId: like.targetId });
                    if (comment) {
                        likeData.targetInfo = {
                            content: comment.content,
                            videoID: comment.videoID,
                            likeNumber: comment.likeNumber
                        };
                    }
                }
                
                return likeData;
            })
        );

        return {
            success: true,
            likes: likesWithDetails,
            pagination: result.pagination
        };
    } catch (error) {
        return { success: false, message: '获取点赞历史失败：' + error.message };
    }
}

/**
 * 获取热门内容
 * @param {string} targetType - 目标类型
 * @param {number} timeRange - 时间范围（天数）
 * @param {number} limit - 限制数量
 * @returns {Object} 热门内容
 */
async function getPopularContent(targetType, timeRange = 7, limit = 20) {
    try {
        const result = await Likes.getPopularContent(targetType, timeRange, limit);
        
        if (!result.success) {
            return result;
        }

        // 获取详细信息
        const popularWithDetails = await Promise.all(
            result.popular.map(async (item) => {
                let targetInfo = null;
                
                if (targetType === 'video') {
                    const video = await Videos.findOne({ videoID: item._id });
                    if (video) {
                        targetInfo = {
                            videoID: video.videoID,
                            title: video.title,
                            content: video.content,
                            path: video.path,
                            viewCount: video.viewCount,
                            likeCount: video.likeCount,
                            publishTime: video.publishTime
                        };
                    }
                } else if (targetType === 'comment') {
                    const comment = await Comments.findOne({ commentId: item._id });
                    if (comment) {
                        targetInfo = {
                            commentId: comment.commentId,
                            content: comment.content,
                            videoID: comment.videoID,
                            userId: comment.userId,
                            likeNumber: comment.likeNumber,
                            createAt: comment.createAt
                        };
                    }
                }
                
                return {
                    targetId: item._id,
                    likeCount: item.likeCount,
                    latestLike: item.latestLike,
                    targetInfo
                };
            })
        );

        return {
            success: true,
            popular: popularWithDetails.filter(item => item.targetInfo !== null)
        };
    } catch (error) {
        return { success: false, message: '获取热门内容失败：' + error.message };
    }
}

/**
 * 删除点赞记录
 * @param {number} userId - 用户ID
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 * @returns {Object} 删除结果
 */
async function deleteLike(userId, targetType, targetId) {
    try {
        const result = await Likes.deleteLike(userId, targetType, targetId);
        
        if (!result.success) {
            return result;
        }

        // 更新目标的点赞数
        await updateTargetLikeCount(targetType, targetId);

        return {
            success: true,
            message: '删除点赞记录成功'
        };
    } catch (error) {
        return { success: false, message: '删除点赞记录失败：' + error.message };
    }
}

/**
 * 更新目标的点赞数
 * @param {string} targetType - 目标类型
 * @param {number} targetId - 目标ID
 */
async function updateTargetLikeCount(targetType, targetId) {
    try {
        const stats = await Likes.getLikeStats(targetType, targetId);
        
        if (stats.success) {
            if (targetType === 'video') {
                await Videos.updateOne(
                    { videoID: targetId },
                    { likeCount: stats.stats.likes }
                );
            } else if (targetType === 'comment') {
                await Comments.updateOne(
                    { commentId: targetId },
                    { 
                        likeNumber: stats.stats.likes,
                        unlikeNumber: stats.stats.dislikes
                    }
                );
            }
        }
    } catch (error) {
        console.error('更新点赞数失败：', error);
    }
}

/**
 * 获取操作消息
 * @param {string} action - 操作类型
 * @param {number} likeStatus - 点赞状态
 * @returns {string} 消息
 */
function getActionMessage(action, likeStatus) {
    if (action === 'cancelled') {
        return '取消成功';
    } else if (action === 'created' || action === 'updated') {
        return likeStatus === 1 ? '点赞成功' : '点踩成功';
    }
    return '操作成功';
}

module.exports = {
    toggleLike,
    getLikeStatus,
    batchGetLikeStatus,
    getLikeStats,
    getUserLikeHistory,
    getPopularContent,
    deleteLike
};